<?php

use Phinx\Db\Adapter\MysqlAdapter;
use think\migration\Migrator;

class Admin extends Migrator{

	/**
	 * Change Method.
	 * Write your reversible migrations using this method.
	 * More information on writing migrations is available here:
	 * http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
	 * The following commands can be used in this method and Phinx will
	 * automatically reverse them when rolling back:
	 *    createTable
	 *    renameTable
	 *    addColumn
	 *    renameColumn
	 *    addIndex
	 *    addForeignKey
	 * Remember to call "create()" or "update()" and NOT "save()" when working
	 * with the Table class.
	 */
	public function change(){
		if($this->hasTable('admin')){
			//			$this->dropTable('admin');
			return;
		}

		$table = $this->table('admin', [
			'engine'    => 'InnoDB',
			'signed'    => false,
			'encoding'  => 'utf8mb4',
			'collation' => 'utf8mb4_general_ci',
			'comment'   => '后台管理员表',
		]);

		$table->addColumn('username', 'char', [
			'limit'   => 48,
			'comment' => '用户名',
		])
			->addColumn('password', 'char', [
				'limit'   => 32,
				'comment' => '密码',
			])
			->addColumn('status', 'boolean', [
				'limit'   => MysqlAdapter::INT_TINY,
				'signed'  => false,
				'default' => 0,
				'comment' => '用户状态',
			])
			->addColumn('login_count', 'integer', [
				'limit'   => 11,
				'signed'  => false,
				'default' => 0,
				'comment' => '登录次数',
			])
			->addColumn('login_time', 'integer', [
				'limit'   => 11,
				'signed'  => false,
				'default' => 0,
				'comment' => '最后登录时间',
			])
			->addColumn('login_ip', 'biginteger', [
				'limit'   => 20,
				'signed'  => false,
				'default' => 0,
				'comment' => '最后登录IP',
			])
			->addColumn('create_ip', 'biginteger', [
				'limit'   => 20,
				'signed'  => false,
				'default' => 0,
				'comment' => '注册IP',
			])
			->addColumn('delete_time', 'integer', [
				'limit'   => 11,
				'signed'  => false,
				'default' => 0,
				'comment' => '删除时间',
			])
			->addColumn('update_time', 'integer', [
				'limit'   => 11,
				'signed'  => false,
				'default' => 0,
				'comment' => '更新时间',
			])
			->addColumn('create_time', 'integer', [
				'limit'   => 11,
				'signed'  => false,
				'default' => 0,
				'comment' => '创建时间',
			])
			->addIndex(['username'], ['unique' => true])
			->create();

		$this->initData($table);
	}

	/**
	 * @param \think\migration\db\Table $table
	 */
	private function initData($table){
		$table->insert([
			'id'          => 1,
			'username'    => 'admin',
			'password'    => \app\common\model\Admin::encrypt('123456'),
			'status'      => 1,
			'login_count' => '0',
			'login_time'  => 0,
			'login_ip'    => 0,
			'create_ip'   => 0,
			'delete_time' => 0,
			'update_time' => 0,
			'create_time' => time(),
		])->save();
	}
}
